"use client";

import { Loader2, TriangleAlert } from "lucide-react";
import Link from "next/link";

import { useProjectQuery } from "@/hooks/use-project-query";
import { downloadCSV } from "@/lib/csv";
import type { ProjectDetail } from "@/lib/types";

interface ProjectDetailViewProps {
  initialProject: ProjectDetail;
}

const METRIC_LABELS: Record<keyof ProjectDetail["metrics"], { title: string; description: string }> = {
  today: {
    title: "今日产值",
    description: "当日确认的产值合计",
  },
  week: {
    title: "本周累计",
    description: "周一至今的产值总计",
  },
  month: {
    title: "本月累计",
    description: "自然月内的产值总计",
  },
};

export function ProjectDetailView({ initialProject }: ProjectDetailViewProps) {
  const { data: project, isLoading, error } = useProjectQuery(initialProject.id, initialProject);
  const current = project ?? initialProject;
  const metrics = current.metrics;
  const outputs = current.recentOutputs ?? [];

  const exportRows = outputs.map((item) => ({
    projectName: item.projectName,
    reporterName: item.reporterName,
    date: item.date,
    value: item.value,
    note: item.note ?? "",
  }));

  const handleExport = () => {
    if (outputs.length === 0) {
      return;
    }

    downloadCSV(
      `project-${current.id}-outputs.csv`,
      [
        { key: "projectName", header: "项目" },
        { key: "reporterName", header: "上报人" },
        { key: "date", header: "日期" },
        { key: "value", header: "产值" },
        { key: "note", header: "备注" },
      ],
      exportRows,
    );
  };

  if (isLoading && !project) {
    return (
      <div className="flex min-h-[200px] items-center justify-center rounded-lg border border-border bg-card/60">
        <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-2">
        <Link href="/schedule" className="text-xs text-muted-foreground hover:text-primary">
          ← 返回排产总览
        </Link>
        <div className="space-y-2">
          <h1 className="text-2xl font-semibold text-foreground">{current.name}</h1>
          {current.description ? (
            <p className="text-sm text-muted-foreground">{current.description}</p>
          ) : null}
          <div className="flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
            <span>项目负责人：{current.managerName ?? "--"}</span>
            <span>状态：{current.isActive ? "启用" : "停用"}</span>
            {current.monthlyTarget != null ? (
              <span>当月目标：{current.monthlyTarget.toLocaleString()}</span>
            ) : null}
            {current.currentValue != null ? (
              <span>本月累计：{current.currentValue.toLocaleString()}</span>
            ) : null}
            {current.progressPercentage != null ? (
              <span>完成度：{current.progressPercentage}%</span>
            ) : null}
          </div>
        </div>
      </div>

      {error ? (
        <div className="flex items-center gap-2 rounded-lg border border-destructive/40 bg-destructive/5 px-4 py-3 text-xs text-destructive">
          <TriangleAlert className="h-4 w-4" />
          项目数据刷新失败，显示为最近一次成功加载的内容。
        </div>
      ) : null}

      <div className="grid gap-4 md:grid-cols-3">
        {(Object.keys(METRIC_LABELS) as (keyof ProjectDetail["metrics"])[]).map((key) => {
          const metric = METRIC_LABELS[key];
          return (
            <div key={key} className="rounded-lg border border-border bg-card p-4 shadow-sm">
              <p className="text-xs font-medium uppercase text-muted-foreground">{metric.title}</p>
              <p className="mt-2 text-2xl font-semibold text-foreground">
                {metrics[key].toLocaleString(undefined, { maximumFractionDigits: 2 })}
              </p>
              <p className="mt-1 text-xs text-muted-foreground">{metric.description}</p>
            </div>
          );
        })}
      </div>

      <div className="space-y-4 rounded-lg border border-border bg-card p-4 shadow-sm">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <p className="text-sm font-medium text-foreground">最近上报</p>
            <p className="text-xs text-muted-foreground">展示近 20 条上报记录，方便快速核对。</p>
          </div>
          <button
            type="button"
            onClick={handleExport}
            className="inline-flex items-center rounded-md bg-primary px-3 py-2 text-xs font-medium text-primary-foreground transition hover:bg-primary/90"
            disabled={outputs.length === 0}
          >
            导出 CSV
          </button>
        </div>

        {outputs.length === 0 ? (
          <div className="rounded-lg border border-dashed border-border bg-background p-6 text-sm text-muted-foreground">
            暂无上报记录，提交第一条产值后即可在此查看。
          </div>
        ) : (
          <div className="overflow-hidden rounded-lg border border-border">
            <table className="min-w-full divide-y divide-border text-sm">
              <thead className="bg-muted/40 text-muted-foreground">
                <tr>
                  <th className="px-4 py-3 text-left font-medium">日期</th>
                  <th className="px-4 py-3 text-left font-medium">上报人</th>
                  <th className="px-4 py-3 text-left font-medium">产值</th>
                  <th className="px-4 py-3 text-left font-medium">备注</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border bg-card">
                {outputs.map((item) => (
                  <tr key={item.id}>
                    <td className="px-4 py-3 text-muted-foreground">
                      {new Date(item.date).toLocaleDateString()}
                    </td>
                    <td className="px-4 py-3 text-muted-foreground">{item.reporterName}</td>
                    <td className="px-4 py-3 text-muted-foreground">{item.value.toLocaleString()}</td>
                    <td className="px-4 py-3 text-xs text-muted-foreground">{item.note ?? "--"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
